local filename = "givemoney.lua"

local timetool = require "timetool"
local skynet = require "skynet"
local cluster = require "skynet.cluster"
local filelog =require "filelog"
local redisdao = require "redisdao"
local md5 = require "md5"
require "pubenum"

local json = require "cjson.safe"
json.encode_sparse_array(true,1,1)

local service = nil
local CMD = {
	service = nil
}

--是否处理中
local is_handling = false

local function get_givemoney_open()
    local is_open = 1   --默认打开
    local key = "givemoney_is_open"
    local result, result_data = redisdao.query_data(".gmmqredis", "get", key)
    if result and result_data then
        is_open = tonumber(result_data) or 1
    end
    return is_open
end

local function get_use_givemoney_level()
    local min_level = 0
    local key = "use_givemoney_level"
    local result, result_data = redisdao.query_data(".gmmqredis", "get", key)
    if result and result_data then
        min_level = tonumber(result_data) or 0
    end
    return min_level
end



--
----处理玩家赠送金币
--
local function handle_givemoney(rid, msgbody)
    if not msgbody or not msgbody.target_rid then
        return {retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "转账玩家ID不能为空"}
    end

    local target_rid = tonumber(msgbody.target_rid) or 0
    
    --不能给自己赠送
    if target_rid == rid then
        return {retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "不能给自己转账"}
    end
    
    --验证保险箱密码,默认不验证
    --givemoney_is_auth赠送是否需要验证密码 1需要 非1需要
    local _,givemoney_is_auth = redisdao.query_data(".gmmqredis", "get", "givemoney_is_auth")
    if tonumber(givemoney_is_auth or 0) == 1 then
        if not msgbody.lock_pwd or not service.money.lock_password or service.money.lock_password == "" then
            return {retcode = EErrCode.ERR_INVALID_PASSWORD, retstr = "保险箱密码未设置或密码错误！"}
        end
        local lock_password = md5.sumhexa(msgbody.lock_pwd .. rid)
        if lock_password ~= service.money.lock_password then
            return {retcode = EErrCode.ERR_INVALID_PASSWORD, retstr = "密码错误！"}
        end
    end

    ---检查redis中是否开启 givemoney
    local is_open = get_givemoney_open()
    if not is_open or is_open <= 0 then
        return { retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "此功能尚未开放!" }
    end

    ---判断level
    if service.info.level < get_use_givemoney_level() then
        return { retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "权限不够" }
    end
    
    --获得赠送目标玩家姓名
    local up_rid = 0
    local target_rolename = ""
    local _,targetinfos = skynet.pcall(cluster.call, "datanode", ".router", "select_rk", target_rid, "rs_info", true)
	if targetinfos and targetinfos[1] ~= 0 and targetinfos[2] then
        up_rid = tonumber(targetinfos[2][target_rid].agencyrid) or 0
        target_rolename = tostring(targetinfos[2][target_rid].rolename) or ""
    else
        return { retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "转账玩家ID不存在" }
    end

    --只能给上级或下级增送
    --givemoney_is_limit 赠送是否限制在上下级间，1是 非1 否
    local _,givemoney_is_limit = redisdao.query_data(".gmmqredis", "get", "givemoney_is_limit")
    if tonumber(givemoney_is_limit or 0) == 1 then
        if target_rid ~= service.info.agencyrid or target_rid < 100000 then
            if up_rid ~= rid or up_rid < 100000 then
                return {retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "只能给直属上级或下级转账"}
            end
        end
    end

    --赠送默认最少10元
    local _,givemoney_min_money = redisdao.query_data(".gmmqredis", "get", "givemoney_min_money")
    givemoney_min_money = tonumber(givemoney_min_money) or 1000
    local value = tonumber(msgbody.value) or 0
    if value < givemoney_min_money then
         return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "转账金额最少" .. math.floor(givemoney_min_money/100) .. "元"}
    end
    if value % 100 ~= 0  then
        return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "转账金额必须是整数"}
    end
    
    --获得今日最大赠送额度,默认1000元
    local keyname = (rid or 0) .. ":givemoney_daily_money"
    local _,givemoney_daily_money = redisdao.query_data(".gmmqredis", "get", keyname)
    givemoney_daily_money = tonumber(givemoney_daily_money) or 100000
    
    --获得今日累积赠送的金额
    local curtime = timetool.get_time()
    local _, record_data = redisdao.query_data(".gmmqredis", "get", (rid or 0) .. ":givemoneyrecord")
    local givemoneyrecord = json.decode(record_data or "{}") or { }
    local curday = os.date("%d", curtime)
    if givemoneyrecord.record_time then
        local lasttime = tonumber(givemoneyrecord.record_time)
        local lastday = os.date("%d", lasttime)
        if lastday ~= curday or (curtime - lasttime) > 86400 then
            givemoneyrecord.total_value = 0
        end
    end
    givemoneyrecord.total_value = tonumber(givemoneyrecord.total_value) or 0
    
    --检测是否超过每日赠送额度
    local remain_give_money = givemoney_daily_money - givemoneyrecord.total_value
    if value > remain_give_money then
        if remain_give_money <= 0 then
            return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "已达到今日最大转账额度" }
        else
            return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "今日最多还能转账" .. math.floor(remain_give_money / 100) .. "元" }
        end
    end
    
    --检测钱是否足够
    local _,givemoney_init_base = redisdao.query_data(".gmmqredis", "get", "givemoney_init_base")
    local basemoney = tonumber(givemoney_init_base) or 10000
    local limit_value = value + basemoney
    local cur_money = service.money.diamond or 0
    if cur_money < limit_value then
        return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "超出最大可转账金额"}
    end

    --扣除玩家钱
    local subvalue = -value
    local beginvalue = cur_money
    local setargs = service:change_money({diamond = subvalue}, { })
    if setargs then
        --保存赠送记录
        local comment = { }
        local now = timetool.get_time()
        comment.table_uuid = "gatenode" .. "_" .. 0 .. "_" .. 0 .. "_" .. now
        --格式：日志类型，rid，level，变化值，初始值，结束值，agent初始值，agent结束值，银行当前值，table_uuid,当前时间
        local logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%d", EDiamondChange.GIVE_MONEY, rid, service.info.level,
        subvalue, 0, 0,beginvalue, service.money.diamond, service.money.lock_diamond, comment.table_uuid, now, target_rid)

        --保存赠送记录
        local tmfmt = tostring( os.date("%m%d%H%M%S",now))
        local rndcode = tostring(math.random(100000,999999))
        local tradeid = tmfmt .. "_" .. rid .. "_" .. target_rid .. "_" .. value .. "_" .. rndcode
        local fields = {
            recvrid = target_rid,
            tradeid = tradeid,
            sendname = service.info.rolename,
            recvname = target_rolename,
            give_type = EGiveMoneyType.EGIVEMONEY_TYPE_PLAYER_GIVING,
            give_value = value,
            begin_value = beginvalue,
            end_value = service.money.diamond,
            current_state = EGiveMoneySate.EGIVEMONEY_STATE_WAIT_DRAW,
            remark = "玩家转账",
        }
        local record_keyid = skynet.call(".givesystem", "lua", "newgiving", rid, fields) or 0
        
        --保存日志到文件
        logstr = logstr .. "," .. record_keyid
        skynet.send(".diamondlog", "lua", "write", logstr)
        
        --保存今日赠送记录
        givemoneyrecord.record_time = curtime
        givemoneyrecord.total_value = givemoneyrecord.total_value + value
        redisdao.query_data(".gmmqredis", "set", (rid or 0) .. ":givemoneyrecord", json.encode(givemoneyrecord))
        
        return {}
    end
	
	return {retcode = EErrCode.ERR_SYSTEM_ERROR, retstr = "转账失败，请稍后重试"}
end

--
--处理玩家赠送金币
--
function CMD.process(rid, msgbody)
	if not service then
		service = CMD.service
	end

    --正在处理中
    if is_handling then
        return { }
    else
        is_handling = true
    end

    --处理
    local response = handle_givemoney(rid, msgbody)
    is_handling = false

    return response
end

return CMD